package org.yanh.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yanh.es.domain.Address;
import org.yanh.es.domain.Poem;
import org.yanh.es.mapper.PoemMapper;
import org.yanh.es.service.IPoemService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class PoemServiceImpl extends ServiceImpl<PoemMapper, Poem> implements IPoemService {

    @Autowired
    private PoemMapper poemDAO;
    @Autowired
    private RestHighLevelClient client;
    @Override
    public List<Poem> findByPage(Integer start, Integer size) {
        int pagestart = (start - 1) * size;
        return poemDAO.findByPage(pagestart, size);
    }

    @Override
    public Long findTotalCounts() {
        return poemDAO.findTotalCounts();
    }

    @Override
    public List<Poem> findAll() {
        return poemDAO.findAll();
    }

    @Override
    public List<Poem> findByKeywords(String content, String type, String author) {
        //定义list
        List<Poem> lists = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest("poems");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            //搜索条件为空指定查询条件
            if (StringUtils.isEmpty(content)) {
                //设置为查询所有
                sourceBuilder.query(QueryBuilders.matchAllQuery());
            } else {
                //设置为多字段检索
                sourceBuilder.query(QueryBuilders.multiMatchQuery(content, "name", "content", "authordes"));
            }

            //指定过滤条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (!StringUtils.isEmpty(author)) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("author",author));
            }
            if (!StringUtils.isEmpty(type)) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("type",type));
            }
            //指定过滤
            sourceBuilder.postFilter(boolQueryBuilder);

            //指定高亮
            sourceBuilder.highlighter(new HighlightBuilder().field("*").requireFieldMatch(false).preTags("<span style='color:red;'>").postTags("</span>"));

            //指定显示记录
            sourceBuilder.size(100);

            //指定搜索类型
            searchRequest.source(sourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 根据状态和数据条数验证是否返回了数据
            if (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getTotalHits().value > 0) {
                SearchHits hits = searchResponse.getHits();
                for (SearchHit hit : hits) {
                    // 将 JSON 转换成对象
                    Poem poem = JSON.parseObject(hit.getSourceAsString(), Poem.class);
                    //获取高亮字段
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    if (highlightFields.containsKey("name")) {
                        poem.setName(highlightFields.get("name").fragments()[0].toString());
                    }
                    if (highlightFields.containsKey("author")) {
                        poem.setAuthor(highlightFields.get("author").fragments()[0].toString());
                    }
                    if (highlightFields.containsKey("authordes")) {
                        poem.setAuthordes(highlightFields.get("authordes").fragments()[0].toString());
                    }
                    if (highlightFields.containsKey("content")) {
                        poem.setContent(highlightFields.get("content").fragments()[0].toString());
                    }
                    lists.add(poem);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lists;
    }


}
